#!/usr/bin/python3

import os
import subprocess

'''1.show ip file and directory'''
dir = "/etc/sysconfig/network-scripts/"
show_dir = os.walk(dir)
for i in show_dir:
    file = i[2]
    ipfile=file[-1]
    print ("ip file name is : %s" % ipfile)
'''1.1backup ip configuration file'''
back_option = input("you need backup ip configuratin file:[y/n]")
if back_option == 'y':
    backup = os.system("/usr/bin/cp /etc/sysconfig/network-scripts/%s /root/" % ipfile)
    ip_path = "/etc/sysconfig/network-scripts/%s already backup /root/" % ipfile
    print ("ip config directory is : %s" % ip_path)
else:
    print ("the ip configuration no backup")
    
'''2.config ip'''
option = input("Should you override the IP configuration file [y/n]:")
if option == 'y': 
    ip_path = "/etc/sysconfig/network-scripts/%s" % ipfile
    print (ip_path)
    ip = input("please input ip address:")
    net = input("please input ip netmask:")
    gate = input("please input ip gateway:")
    dns = input("please input ip dns1:")
    '''2.1write ip information and flush network service'''
    f = open(ip_path,"a+")
    addre = "IPADDR=%s\nNETMASK=%s\nGATEWAY=%s\nDNS1=%s" % (ip,net,gate,dns)
    f.write(addre)
    f.flush()
    f.close()
    os.system("service network restart")
    ip = subprocess.getoutput("ip addr").split("\n")[-4]
    if 'inet' and 'brd' and 'global' in ip:
        print ("you configuration ip information is success")
        print (addre)
    else:
        print ("you configuration ip information is failed!\nplease check manually!")
elif option == 'n':
    print ("you option quit")
    exit()
else:
    print ("input error,exit!!")
    exit()
